import React, {Component} from 'react'
import {
    Animated,
    DeviceEventEmitter,
    Dimensions,
    Easing,
    Image,
    ListView,
    ScrollView,
    StyleSheet,
    Text,
    TouchableHighlight,
    TouchableOpacity,
    View
} from "react-native";
import StyleUtils from "../../res/styles/StyleUtils";
import Navigation from "../../custom/Navigation";
import ViewUtils from "../../utils/ViewUtils";
import IparNetwork, {getSynPaysSellerAuth, SERVER_TYPE} from "../../httpUtils/IparNetwork";
import I18n from "../../res/language/i18n";
import CommonUtils from "../../common/CommonUtils";
import AlertDialog from "../../custom/AlertDialog";
import IparImageView from "../../custom/IparImageView";

let width = Dimensions.get('window').width;

export default class ShippingMethodPage extends Component {

    constructor(props) {
        super(props);

        this.iparNetwork = new IparNetwork();
        let ds = new ListView.DataSource({
            rowHasChanged: (r1, r2) => r1 !== r2
        });
        this.state = {
            globalGoodsData: ds,
            alertVisible: false,
            alertMsg: '',
            alertTypeIsCancel: true,
            shippingData: null,
            shippingResultData: null,
            shippingAmount: 0,
        }
    }


    onClick(rowData) {

        let props = this.props;

        //notCount是 是不是 不算运费的意思
        if (rowData.expressService === 'china_post' || rowData.expressService === 'pic_up' || props.notCount) {
            props.callback && props.callback(rowData, null, null);
            props.navigator.pop();
        } else {
            this.getShippingInfo(rowData)
        }
    }


    /**
     * 计算运费
     * */
    getShippingInfo(rowData) {

        CommonUtils.showLoading();


        let _items = [];
        let goodsArray = this.props.dataSource;
        for (let i = 0, len = goodsArray.length; i < len; i++) {
            let _goods = goodsArray[i];
            _items.push({
                quantity: _goods.goods_number,  //单个产品数量
                weight: _goods.goods_weight,   // g
                valueAmount: (_goods.goods_pv).toFixed(1), // 每个产品价格
                originCountry: _goods.origin ? _goods.origin : 'CN', //
                tariffNumber: _goods.hs_code, //hs
                description: _goods.description // 说明
            })
        }


        let currencyInfo = this.currencyInfo;
        let data = {
            "addressId": this.props.shippingAddressData.id,
            "expressId": rowData.id,
            "currency": currencyInfo.currency_name,
            "items": _items
        };


        this.iparNetwork.getPostJson(SERVER_TYPE.logistics + 'shipping/calculation', data)
            .then((result) => {
                let error = true;
                let _msg = I18n.t('toast.isErrorShippingAddress');
                let _shippingMethod = null;
                if (result && (result.shipping || result.explain)) {

                    _shippingMethod = result.shipping;

                    if (rowData.expressService === 'fedex_international_economy' ||
                        rowData.expressService === 'fedex_international_priority' ||
                        rowData.expressService === 'usps_first_class_international' ||
                        rowData.expressService === 'usps_priority_mail_international' ||
                        rowData.expressService === 'usps_priority_mail_express_inter') {


                        this.getMyAmount(currencyInfo.currency_name, result.shipping, rowData, result);
                        return;
                    }
                    _msg = I18n.t('default.shippingAmount') +
                        (_shippingMethod.toFixed(2)) + ' ' + currencyInfo.currency_code;
                    error = false
                }
                CommonUtils.dismissLoading();

                this.setState({

                    alertMsg: _msg,
                    alertTypeIsCancel: error,
                    shippingAmount: _shippingMethod,
                    alertVisible: true,
                    shippingData: rowData,
                    shippingResultData: result,
                });
            })
            .catch((error) => {
                CommonUtils.dismissLoading();

                console.log('ConfirmOrderPage---getShippingInfo--error: ', error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
            })


    }


    /**
     *
     * 获取本国家的价格
     * */
    getMyAmount(currency_name, USDAmount, shippingData, shippingResultData) {

        this.iparNetwork.getRequest(SERVER_TYPE.synPays + 'Forex/Latest?',
            'APIKEY=' + getSynPaysSellerAuth(this.country, 1) + '&Source=USD&Amount=' + USDAmount)
            .then((result) => {
                CommonUtils.dismissLoading();

                if (result.ApiResponseCode === 200) {
                    let quote = parseFloat(result.data.quotes[currency_name]);
                    this.setState({
                        alertMsg: I18n.t('default.shippingAmount') +
                            (quote.toFixed(2)) + ' ' + currency_name,
                        alertTypeIsCancel: false,
                        shippingAmount: quote,
                        alertVisible: true,
                        shippingData: shippingData,
                        shippingResultData: shippingResultData,
                    });
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
                }
            })
            .catch((error) => {
                CommonUtils.dismissLoading();

                console.log('ConfirmOrderPage---getMyAmount--error: ', error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
            })


    }


    componentDidMount() {
        CommonUtils.getAcyncInfo('country_iso')
            .then((country) => {
                //countryShippingData是我要只是这国家的物流（不管origin/country）
                let iso = this.props.countryShipping;
                let origin;
                if (!iso) {
                    iso = this.props.shippingAddressData.iso;
                    origin = this.props.origin;
                }
                this.country = country;
                CommonUtils.showLoading();
                let params = 'express?country=' + iso;
                if (!this.props.countryShipping) {
                    params = params + '&origin=' + origin
                }
                this.iparNetwork.getRequest(SERVER_TYPE.logistics, params + '&show_app=1')
                    .then((result) => {
                        CommonUtils.dismissLoading();

                        if (result && !result.code) {
                            let data = [];
                            if (this.props.notShowPicup) {
                                for (let dataRow of  result) {
                                    if (dataRow.expressService != 'self_send' && dataRow.expressService != 'pic_up') {
                                        data.push(dataRow)
                                    }
                                }
                            } else {
                                for (let dataRow of  result) {
                                    if (dataRow.expressService != 'self_send') {
                                        data.push(dataRow)
                                    }
                                }
                            }

                            this.setState({
                                globalGoodsData: this.state.globalGoodsData.cloneWithRows(data)
                            })
                        }
                    })
                    .catch((error) => {

                        CommonUtils.dismissLoading();
                        console.log(error);
                    })
            });


        if (!this.props.currencyInfo) {
            CommonUtils.getAcyncInfo('getPv')
                .then((result) => {
                    if (result) {
                        let parse = JSON.parse(result);
                        this.currencyInfo = parse;
                    }
                });
        } else {
            this.currencyInfo = this.props.currencyInfo
        }

    }

    render() {
        return (
            <View style={StyleUtils.flex}>
                <Navigation
                    onClickLeftBtn={() => {
                        this.props.navigator.pop()
                    }}
                />
                <ScrollView>
                    {ViewUtils.getTitleView(I18n.t('default.shippingCompany'), I18n.t('default.shippingMethodDeliver'))}

                    {/**ListView horizontal*/}
                    <ListView
                        contentContainerStyle={styles.gridListStyle}
                        dataSource={this.state.globalGoodsData}
                        renderRow={(rowData, sectionID, rowID) => this._renderTopRow(rowData, rowID)}
                    />

                </ScrollView>

                <AlertDialog
                    contentTv={this.state.alertMsg}
                    leftBtnOnclick={
                        !this.state.alertTypeIsCancel ? () => {
                            let state = this.state;
                            this.props.callback && this.props.callback(state.shippingData, state.shippingResultData, state.shippingAmount);
                            this.props.navigator.pop()
                        } : null}
                    visible={this.state.alertVisible}
                    singleBtnOnclick={this.state.alertTypeIsCancel ? () => {
                        this.setState({
                            alertVisible: false,
                        })
                    } : null}
                    requestClose={() => this.setState({alertVisible: false})}/>

            </View>
        )
    }

    _renderTopRow(rowData, rowID) {
        let viewWidth = (width / 2) - 24;
        return (
            <TouchableOpacity
                onPress={() => this.onClick(rowData)}
                style={{
                    marginLeft: 16,
                    marginTop: 16,
                }}
            >


                {/*<Image*/}
                {/*resizeMode="contain"*/}
                {/*style={{*/}
                {/*width: viewWidth,*/}
                {/*height: viewWidth / 2.5,*/}
                {/*borderWidth: 1,*/}
                {/*borderColor: '#e5e5e5',*/}
                {/*resizeMode: 'contain'*/}
                {/*}}*/}
                {/*source={{uri: rowData.icon}}/>*/}

                <IparImageView
                    httpUrlNotShow={true}
                    style={{
                        borderColor: '#e5e5e5',
                        borderWidth: 1,
                    }}
                    width={viewWidth}
                    height={viewWidth / 2.5}
                    url={rowData.icon}/>

                <Text style={[styles.text, StyleUtils.smallFont, {width: viewWidth}]}>
                    {rowData.name}
                </Text>
            </TouchableOpacity>
        )
    }
}
const styles = StyleSheet.create({
    gridListStyle: {
        flexDirection: 'row',
        flexWrap: 'wrap',
    },
    text: {
        textAlign: 'center',
        fontSize: 16,
        paddingTop: 4,
        color: '#333'
    },


});
